/**
 * Created by BobbyGu on 2017/3/6.
 */
public class VersionCompare {
    public String versionCompare(String version1, String version2) {
        if (version1 == null || version2 == null) {
            System.out.println("版本号不能为空");
            return null;
        }
        String v1 = getCleanVersion(version1);//获取纯数字的字符串
        String v2 = getCleanVersion(version2);//获取纯数字的字符串
        String[] versionArr1, versionArr2;
        versionArr1 = v1.split("\\.");//用.将数字分组
        versionArr2 = v2.split("\\.");//用.将数字分组
        int size1 = versionArr1.length;
        int size2 = versionArr2.length;
        int sizeMin = size1 < size2 ? size1 : size2;
        //一组一组的比较号码大小
        for (int i = 0; i < sizeMin; i++) {
            int i1 = Integer.parseInt(versionArr1[i]);
            int i2 = Integer.parseInt(versionArr2[i]);
            if (i1 > i2)
                return version1;//如果第一个组里的数字更大返回第一个版本号
            else if (i1 < i2)
                return version2;//如果第二个组里的数字更大返回第二个版本号
        }
        if (size1 > size2) {
            return version1;//第一个版本号位数更多
        } else if (size2 > size1) {
            return version2;//第二个版本号位数更多
        }
        //两个版本号一样返回其中一个版本号
        return version1;
    }

    private String getCleanVersion(String version) {
        for (int i = 0; i < version.length(); i++) {
            if (version.charAt(i) < '0' || version.charAt(i) > '9')
                i++;
            return version.substring(i);
        }
        return version;
    }

    public static void main(String[] args) {
        //测试用例
        String[] version1Test = new String[]{
                "v1.0.1", "v11.232.11", "43.42.211", null};
        String[] version2Test = new String[]{
                "v2.0.1", "11.232.1221.123312", "4223.42.211", "1.3.3"};
        VersionCompare vc = new VersionCompare();
        for (int i = 0; i < 4; i++) {
            String result = vc.versionCompare(version1Test[i], version2Test[i]);
            if (result != null)
                System.out.println("较大的版本号是：" + result);
        }
    }
}
